from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy.exc import SQLAlchemyError
import logging
from contextlib import asynccontextmanager

# 导入路由
from api import api_router

# 导入数据库
from database import engine, Base

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 创建数据库表
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行
    try:
        # 创建数据库表
        Base.metadata.create_all(bind=engine)
        logger.info("数据库表创建成功")
    except Exception as e:
        logger.error(f"创建数据库表时出错: {str(e)}")
        raise
    
    yield
    
    # 关闭时执行
    logger.info("应用关闭")

# 创建FastAPI应用
app = FastAPI(
    title="无人机管理系统API",
    description="一个基于FastAPI的无人机管理系统后端API",
    version="1.0.0",
    lifespan=lifespan,
    swagger_ui_css_url="/static/swagger-ui.css",
    swagger_ui_bundle_url="/static/swagger-ui-bundle.js"
)

# 挂载静态文件目录
import os
static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
if not os.path.exists(static_dir):
    os.makedirs(static_dir)
app.mount("/static", StaticFiles(directory=static_dir), name="static")

# 配置CORS
origins = [
    "http://localhost",
    "http://localhost:3000",  # 前端开发服务器端口
    "http://localhost:5173",  # Vue开发服务器默认端口
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 全局异常处理
@app.exception_handler(SQLAlchemyError)
async def sqlalchemy_exception_handler(request, exc):
    logger.error(f"数据库错误: {str(exc)}")
    return JSONResponse(
        status_code=500,
        content={"detail": "数据库操作失败"}
    )

@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
    logger.error(f"未处理的异常: {str(exc)}")
    return JSONResponse(
        status_code=500,
        content={"detail": "服务器内部错误"}
    )

# 注册路由
app.include_router(api_router, prefix="/api/v1")

# 根路径
@app.get("/")
async def root():
    return {
        "message": "无人机管理系统API",
        "version": "1.0.0",
        "docs": "/docs"
    }

# 健康检查端点
@app.get("/health")
async def health_check():
    return {"status": "healthy"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)